package light.mvc.controller.workflow;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.mvc.controller.base.BaseController;
import light.mvc.model.workflow.Tfield;
import light.mvc.model.workflow.TformTemplate;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.workflow.FormTemplate;
import light.mvc.pageModel.workflow.ProcessDefinitionModel;
import light.mvc.service.workflow.FormTemplateServiceI;
import light.mvc.service.workflow.ProcessDefinitionServiceI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping({ "/template" })
public class FormTemplateController extends BaseController {
	@Autowired
	private ProcessDefinitionServiceI processDefinitionService;
	@Autowired
	private FormTemplateServiceI formTemplateService;

	@RequestMapping({ "/management" })
	public String list() {
		return "/workflow/templateList";
	}

	@RequestMapping({ "/dataGrid" })
	@ResponseBody
	public Grid dataGrid(FormTemplate formTemplate, PageFilter ph) {
		Grid grid = new Grid();
		grid.setRows(this.formTemplateService.findAll());
		grid.setTotal(Integer.valueOf(grid.getRows().size()).longValue());
		return grid;
	}

	/** 删除，也要删除对应的文件 */
	@RequestMapping({ "/delete" })
	@ResponseBody
	public Json delete(@RequestParam("formTemplateId") String formTemplateId) {
		formTemplateService.delete(Long.valueOf(formTemplateId));
		Json json = new Json();
		json.setSuccess(true);
		return json;
	}

	/** 添加页面 */
	@RequestMapping({ "/addUI" })
	public String addUI() {
		return "/workflow/addTemplate";
	}

	/** 添加页面 */
	@RequestMapping({ "/addUIData" })
	@ResponseBody
	public List<ProcessDefinitionModel> addUIData() {
		// 准备数据
		List<ProcessDefinitionModel> processDefinitionList = processDefinitionService.findAllLatestVersions();
		return processDefinitionList;
	}

	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public Json add(HttpServletRequest req,FormTemplate formTemplate) throws IOException {
		
		if (formTemplate.getFieldCount() > 0) {
			for (int i = 0; i < formTemplate.getFieldCount(); i++) {
				Tfield tfield = new Tfield();
				if (req.getParameter("fieldType" + i ) == null) {
					continue;
				}
				tfield.setName(new String(req.getParameter("fieldType" + i )));
				tfield.setDescription(new String(req.getParameter("fieldContent" + i)));
				formTemplate.getFields().add(tfield);
			}
		}
		formTemplate.setPdid(new String(req.getParameter("pdid")));
		formTemplateService.save(formTemplate);
		Json json = new Json();
		json.setSuccess(true);
		return json;
	}

	/**
	 * 保存上传的文件，使用UUID做为文件名，并返回文件存储的全路径
	 * 
	 * @param upload
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	protected String saveUploadFile(HttpServletRequest req, CommonsMultipartFile upload) throws IllegalStateException, IOException {
		String basePath = req.getSession().getServletContext().getRealPath("/WEB-INF/upload_files/"); // 返回结果最后没有'/'
		String subPath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
		// 如果文件夹不存在，就创建
		File dir = new File(basePath + subPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		String path = basePath + subPath + UUID.randomUUID().toString(); // 使用UUID做为文件名，以解决重名的问题
		File destFile = new File(path);
		// 移动到目的地，return true if and only if the renaming succeeded; false otherwise
		// 如果目标文件存在就会失败返回false.
		// 如果目标文件所在的文件夹不存在，就会失败返回false.
		upload.transferTo(destFile);

		return path;
	}

	/** 下载 */
	@RequestMapping(value = "download", method = RequestMethod.GET)
	@ResponseBody
	public void download(HttpServletRequest request, HttpServletResponse response, String id) throws Exception {
		FormTemplate formTemplate = formTemplateService.getById(Long.valueOf(id));
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String newFileName = new String("申请信息文档.doc");
		String ctxPath = formTemplate.getPath();
		String downLoadPath = ctxPath;
		long fileLength = new File(downLoadPath).length();
		response.setHeader("Content-disposition", "attachment; filename=" + new String(newFileName.getBytes("gb2312"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();

	}

	/** 修改页面 
	 * @throws UnsupportedEncodingException */
	@RequestMapping(value = "editUI")
	public String editUI(@ModelAttribute FormTemplate formTemplate) throws UnsupportedEncodingException {
		// ProcessDefinition processDefinition = processDefinitionService.getProcessDefinition(formTemplate.getId().toString());
//		String proccessInstanceId = URLDecoder.decode(piId, "utf-8");
		String name = URLDecoder.decode(formTemplate.getName(), "utf-8");
		String processDefinitionKey = URLDecoder.decode(formTemplate.getProcessDefinitionKey(),"utf-8");
		formTemplate.setName(name);
		formTemplate.setProcessDefinitionKey(processDefinitionKey);
		return "/workflow/editTemplate";
	}

	/**
	 * 修改
	 * 
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "edit")
	@ResponseBody
	public Json edit(HttpServletRequest req, FormTemplate formTemplate, @RequestParam("file") CommonsMultipartFile file) throws IllegalStateException, IOException {
		// 从数据库中获取原对象
		TformTemplate tformTemplate = formTemplateService.getTformTemplateById(formTemplate.getId());

		// 设置要修改的属性
		tformTemplate.setName(formTemplate.getName());
		tformTemplate.setProcessDefinitionKey(formTemplate.getProcessDefinitionKey());
		if (file != null) {
			// 1，删除老文件
			File myfile = new File(tformTemplate.getPath());

			if (myfile.exists()) {
				myfile.delete();
			}

			// 2，保存并关联新文件
			String path = saveUploadFile(req, file);
			tformTemplate.setPath(path);
		}

		// 更新
		formTemplateService.update(tformTemplate);

		Json json = new Json();
		json.setSuccess(true);
		return json;
	}

	/** 查看流程图（xxx.png） */
	@RequestMapping(value = "showProcessImage", method = RequestMethod.GET)
	public void showProcessImage(HttpServletRequest request, HttpServletResponse response, String id, String fileName, String path) throws Exception {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String decodeId = URLDecoder.decode(id, "utf-8");
		InputStream inputStream = processDefinitionService.getProcessImageResourceAsStream(decodeId);
		bis = new BufferedInputStream(inputStream);
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}

}
